﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Coravel;
using Coravel.Invocable;
using ESoft.Logging;

namespace ESoft.Job
{
    /// <summary>
    /// 任务服务实现类
    /// </summary>
    public class JobService : IJobService
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogging<JobService> _logging;
        /// <summary>
        /// 初始化
        /// </summary>
        public JobService(IServiceProvider serviceProvider, ILogging<JobService> logging)
        {
            _serviceProvider = serviceProvider;
            _logging = logging;
        }

        /// <summary>
        /// 启动任务
        /// </summary>
        /// <param name="jobs"></param>
        /// <param name="assemblies"></param>
        public void StartupJobs(IEnumerable<IJob> jobs, Assembly[] assemblies)
        {
            foreach (var job in jobs)
            {
                var cronAttributes = job.GetType().GetCustomAttributes<CronAttribute>();
                _serviceProvider.UseScheduler(scheduler =>
                {
                    var s = scheduler.ScheduleAsync(async () =>
                    {
                        await job.Invoke();
                    });
                    foreach (var cron in cronAttributes)
                    {
                        s.Cron(cron.CronExpression);
                    }
                }).OnError(err =>
                {
                    _logging.Error(err);
                });
            }
        }

        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="job"></param>
        /// <param name="cron"></param>
        /// <returns></returns>
        public Task AddJobAsync(IJob job, string cron)
        {
            _serviceProvider.UseScheduler(scheduler =>
            {
                scheduler.Schedule<IJob>();
            }).OnError(err =>
            {

            });
            return Task.CompletedTask;
        }
    }
}
